package cn.backpackerxl.servlet;

import cn.backpackerxl.entity.Student;
import cn.backpackerxl.service.StudentService;
import cn.backpackerxl.service.impl.StudentServiceImpl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;


@WebServlet(name = "FileServlet", value = "/file")
public class FileServlet extends HttpServlet {
    private final StudentService service = new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //获取不同的响应操作
        String action = request.getParameter("action");

        //使用反射机制执行不同的响应事件
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出excel格式的数据
     *
     * @param request
     * @param response
     * @throws IOException
     */
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String("学生基本信息表".getBytes(), StandardCharsets.ISO_8859_1) + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Student.class).sheet("学生基本信息表").doWrite(service.downloadStudentInfo());
    }

    /**
     * excel数据导入
     *
     * @param request
     * @param response
     */
    public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getContextPath();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        fileUpload.setFileSizeMax(1024 * 1024 * 3); //设置单个上传最大限制3Mb
        fileUpload.setSizeMax(1024 * 1024 * 10); //设置总的上传限制10Mb

        try {
            List<FileItem> list = fileUpload.parseRequest(request);

            for (FileItem fileItem : list) {
                if (!fileItem.isFormField()) {
                    //是文件，而不是常规表单
                    InputStream inputStream = fileItem.getInputStream();
                    EasyExcel.read(inputStream, Student.class, new AnalysisEventListener<Student>() {

                        @Override
                        public void invoke(Student student, AnalysisContext analysisContext) {
                            //解析每一行excel表格时调用
                            student.setSex(student.getSex().trim().equals("男") ? "0" : "1");
                            int i = service.addStudent(student);
                            if (i == 0) {
                                System.out.println("[\033[36m" + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()) + "\033[0m] \033[42mINFO\033[0m - 导入失败");
                            } else {
                                System.out.println("[\033[36m" + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date()) + "\033[0m] \033[42mINFO\033[0m - 导入成功");
                            }
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            //解析完excel表格时调用
                        }
                    }).sheet().doRead();
                } else {
                    //普通提交，这里不用处理
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.sendRedirect(path);
    }
}
